package server.demo.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import server.demo.dto.ApiResponse;
import server.demo.entity.Station;
import server.demo.service.StationService;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/api/v1/stations")
@CrossOrigin(origins = "*")
public class StationController {
    
    @Autowired
    private StationService stationService;
    
    @GetMapping
    public ApiResponse<List<Station>> getAllStations() {
        try {
            List<Station> stations = stationService.getAllStations();
            return ApiResponse.success(stations);
        } catch (Exception e) {
            return ApiResponse.error("获取车站列表失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/{id}")
    public ApiResponse<Station> getStationById(@PathVariable Long id) {
        try {
            Optional<Station> station = stationService.getStationById(id);
            if (station.isPresent()) {
                return ApiResponse.success(station.get());
            } else {
                return ApiResponse.error("车站不存在");
            }
        } catch (Exception e) {
            return ApiResponse.error("获取车站信息失败: " + e.getMessage());
        }
    }
    
    @GetMapping("/code/{stationCode}")
    public ApiResponse<Station> getStationByCode(@PathVariable String stationCode) {
        try {
            Optional<Station> station = stationService.getStationByCode(stationCode);
            if (station.isPresent()) {
                return ApiResponse.success(station.get());
            } else {
                return ApiResponse.error("车站不存在");
            }
        } catch (Exception e) {
            return ApiResponse.error("获取车站信息失败: " + e.getMessage());
        }
    }
    
    @PostMapping
    public ApiResponse<Station> createStation(@RequestBody Station station) {
        try {
            Station createdStation = stationService.createStation(station);
            return ApiResponse.success("车站创建成功", createdStation);
        } catch (Exception e) {
            return ApiResponse.error("创建车站失败: " + e.getMessage());
        }
    }
    
    @PutMapping("/{id}")
    public ApiResponse<Station> updateStation(@PathVariable Long id, @RequestBody Station station) {
        try {
            Station updatedStation = stationService.updateStation(id, station);
            return ApiResponse.success("车站更新成功", updatedStation);
        } catch (Exception e) {
            return ApiResponse.error("更新车站失败: " + e.getMessage());
        }
    }
    
    @DeleteMapping("/{id}")
    public ApiResponse<Void> deleteStation(@PathVariable Long id) {
        try {
            stationService.deleteStation(id);
            return ApiResponse.success("车站删除成功", null);
        } catch (Exception e) {
            return ApiResponse.error("删除车站失败: " + e.getMessage());
        }
    }
}